/**
 * @Title: AsyncTaskUtil.java
 * @author zengshuai shi
 * @date 2015年10月15日 上午9:32:30
 */
package com.shanghaionstar.mro.util;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;

import com.onstar.cn.api.ThirdpartyService;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.util.AppRUtils;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;

import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.MyPost;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.PlateEngineNumEntity;
import com.onstar.cn.vehicle.util.MroBasicNameValuePair;
import com.onstar.cn.vehicle.util.RequstUtil;
import com.shanghaionstar.enumtype.GaodeType;
import com.shanghaionstar.mro.MrOActivity;
import com.shanghaionstar.mro.bean.MrOConstants;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.LoadCityList;
import com.shanghaionstar.utils.NetConnectUtil;
import com.shanghaionstar.utils.RequestUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zengshuai shi
 * @ClassName: AsyncTaskUtil
 * @Description: TODO
 * @date 2015年10月15日 上午9:32:30
 */
public class MroGaodeRequestUtil {
    private List<MroBasicNameValuePair> pairs = new ArrayList<MroBasicNameValuePair>();
    private Boolean isCityCode = false;
    private Context context;
    private String url, s, sign, szImei;
    private MrOActivity.OnMroOperationCallbackListener operationCallbackListener;
    private Map<String, String> map = new HashMap<String, String>();
    private Handler outsideHandler;
    private PlateEngineNumEntity cacheEntity;

//    private static class AsyncTaskUtilInner {
//        static MroGaodeRequestUtil requestUtil = new MroGaodeRequestUtil();
//    }

    public MroGaodeRequestUtil() {

    }

//    public final static MroGaodeRequestUtil getInstance() {
//        return AsyncTaskUtilInner.requestUtil;
//    }

    private void init(final String type) {
        map.clear();
        pairs.clear();
        ((MrOActivity) context).initMyLocation();
        s = "";
        url = "";
        sign = "";
        if (type.equalsIgnoreCase(GaodeType.Weather.value())) {
            url = MrOConstants.WEATHER_URL;
            if (isCityCode) {
                //230100 310000 230200
                pairs.add(new MroBasicNameValuePair(MrOConstants.ADCODE, "230100"));
                pairs.add(new MroBasicNameValuePair(MrOConstants.LONGITUDE, ""));
                pairs.add(new MroBasicNameValuePair(MrOConstants.LATITUDE, ""));
            } else {
                pairs.add(new MroBasicNameValuePair(MrOConstants.ADCODE, ""));
                String longitude = null, latitude = null;
                if(!CommonUtil.isNull(PreferencesUtls.getInstance(context).getString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_CITY_INFO))) {
                   longitude = String.valueOf(PreferencesUtls.getInstance(context).getString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_LOCATION_LONGITUDE));
                   latitude = String.valueOf(PreferencesUtls.getInstance(context).getString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_LOCATION_LATITUDE));
                }else {
                    Message msg = Message.obtain();
                    msg.what = Constants.LOCATION_FAIL;
                    msg.obj = type;
                    outsideHandler.sendMessage(msg);
                    return;
                }
                pairs.add(new MroBasicNameValuePair(MrOConstants.LONGITUDE, longitude));
                pairs.add(new MroBasicNameValuePair(MrOConstants.LATITUDE, latitude));
            }
            pairs.add(new MroBasicNameValuePair(MrOConstants.CHANNEL, MrOConstants.CHANNEL_KEY));
            for (int i = 0; i < 3; i++) {
                MroBasicNameValuePair pair = pairs.get(i);
                s += pair.getValue();
//                Class<?> classType = MroBasicNameValuePair.class;
//                try {
////                    Method getMethod = classType.getMethod("getValue",new Class[]{});
//                    s += pair.getValue();
////                    s += getMethod.invoke(pair);
//                } catch (NoSuchMethodException e) {
//                    e.printStackTrace();
//                } catch (InvocationTargetException e) {
//                    e.printStackTrace();
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                }

            }
            s = s + "@" + MrOConstants.SIGN_KEY;
            sign = Md5Util.getMD5Str(s);
            pairs.add(new MroBasicNameValuePair(MrOConstants.OUTPUT, MrOConstants.OUTPUT_KEY));
            pairs.add(new MroBasicNameValuePair(MrOConstants.SIGN, sign.toUpperCase()));

            Weather weather = new Weather();
            weather.execute();
        } else if (type.equalsIgnoreCase(GaodeType.Restrictions.value())) {
            url = MrOConstants.RESTRICTIONS_URL + "?";
            map.put("channel", "test");
            if (!CommonUtil.isNull(((MrOActivity)context).util.getCurrCity())) {
                map.put("loc_city", ((MrOActivity)context).util.getCurrCity());
            } else {
                Message msg = Message.obtain();
                msg.what = Constants.LOCATION_FAIL;
                msg.obj = type;
                outsideHandler.sendMessage(msg);
                return;
            }
            if (cacheEntity != null) {
                requestRestrictions(type, cacheEntity);
                cacheEntity = null;
            } else {
                RequestUtil.getInstance().getVehicleInfo(new ResponseHandler() {
                    @Override
                    public void onSuccess(String tag, String json) {
                        PlateEngineNumEntity entity = GsonHelper.fromJson( json,PlateEngineNumEntity.class);
                        requestRestrictions(type, entity);
                    }

                    @Override
                    public void onError(String tag, HttpException e) {
                        notifyNoPlateNum(type, null);
                    }
                }, 15 * 1000, context);
            }
        } else if (type.equalsIgnoreCase(GaodeType.Violation.value())) {
//            TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            szImei = new DeviceUtil(context).getDeviceID();
            if (!CommonUtil.isNull(((MrOActivity)context).util.getCurrCity())) {
                LoadCityList cityList = new LoadCityList(context);
                String city = cityList.findByZhCity(((MrOActivity)context).util.getCurrCity());
                pairs.add(new MroBasicNameValuePair(MrOConstants.CITY, city));
            } else {
                Message msg = Message.obtain();
                msg.what = Constants.LOCATION_FAIL;
                msg.obj = type;
                outsideHandler.sendMessage(msg);
                return;
            }
            if (cacheEntity != null) {
                requestViolation(type, cacheEntity);
                cacheEntity = null;
            } else {
                RequestUtil.getInstance().getVehicleInfo(new ResponseHandler() {
                    @Override
                    public void onSuccess(String tag, String json) {
                        PlateEngineNumEntity entity = GsonHelper.fromJson(json,PlateEngineNumEntity.class);
                        requestViolation(type, entity);
                    }

                    @Override
                    public void onError(String tag, HttpException e) {
                        notifyNoPlateNum(type, null);
                    }
                }, 15 * 1000, context);
            }
        }
    }

    private void requestRestrictions(String type, PlateEngineNumEntity entity) {
        if (CommonUtil.isNull(entity.getLicensePlate())) {
            notifyNoPlateNum(type, entity);
        } else {
//            map.put("plate_num", entity.getLicensePlate());
//            map.put("sid", "12345678");
//            map.put("vehicle_type", context.getString(R.string.mro_vehicle_type));
//            map.put("start_date", "");
//            map.put("end_date", "");
//            map.put("lat", "");
//            map.put("lon", "");
//            List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
//            Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
//
//                @Override
//                public int compare(Map.Entry<String, String> lhs, Map.Entry<String, String> rhs) {
//                    return lhs.getKey().compareTo(rhs.getKey());
//                }
//
//            });
//            for (Map.Entry<String, String> mapping : list) {
//                s += mapping.getValue();
//                if (!CommonUtil.isNull(mapping.getValue())) {
//                    url += mapping.getKey() + "=" + mapping.getValue() + "&";
//                }
//            }
//            s = s + "@" + "123456";
//            sign = Md5Util.getMD5Str(s);
//            url = url.substring(0, url.lastIndexOf("&")) + "&sign=" + sign.toUpperCase();
            getViolationAndRestrictions(entity, GaodeType.Restrictions);
        }
    }

    private void requestViolation(String type, PlateEngineNumEntity entity) {
        if (CommonUtil.isNull(entity.getLicensePlate()) || CommonUtil.isNull(entity.getEngineNumber())) {
            notifyNoPlateNum(type, entity);
        } else {
//            pairs.add(new MroBasicNameValuePair(MrOConstants.LICENSE_PLATE_NUM, entity.getLicensePlate()));
//            pairs.add(new MroBasicNameValuePair(MrOConstants.ENGINE_NUM, entity.getEngineNumber()));
//            pairs.add(new MroBasicNameValuePair(MrOConstants.CHANNEL, MrOConstants.CHANNEL_KEY));
//            pairs.add(new MroBasicNameValuePair(MrOConstants.OUTPUT, MrOConstants.OUTPUT_KEY));
//            s = "";
//            s += pairs.get(1).getValue();
//            s += pairs.get(2).getValue();
//            s += pairs.get(0).getValue();
//            s = s + "@" + MrOConstants.SIGN_KEY;
//            sign = Md5Util.getMD5Str(s);
//            pairs.add(new MroBasicNameValuePair(MrOConstants.SIGN, sign.toUpperCase()));
//            url = MrOConstants.VIOLATION_URL;

//            Violation violation = new Violation();
//            violation.plateNum = entity.getLicensePlate();
//            violation.execute();
            getViolationAndRestrictions(entity, GaodeType.Violation);
        }
    }

    private void notifyNoPlateNum(final String type, PlateEngineNumEntity entity) {
        Message msg = Message.obtain();
        msg.what = Constants.LICENSE_PLATE_NUM_NULL;
        msg.obj = type;
        if (entity != null) {
            Bundle bundle = new Bundle();
            bundle.putString(FinalConfigParams.LICENSE_PLATE_NUM, entity.getLicensePlate());
            bundle.putString(FinalConfigParams.ENGINE_NUM, entity.getEngineNumber());
            msg.setData(bundle);
        }
        outsideHandler.sendMessage(msg);
    }

    public void getResult(String type, MrOActivity.OnMroOperationCallbackListener operationCallbackListener, Context context, Handler handler) {
        this.context = context;
        this.outsideHandler = handler;
        this.operationCallbackListener = operationCallbackListener;
        init(type);
    }

    public void cachePlateEngineNumEntity(PlateEngineNumEntity entity) {
        cacheEntity = entity;
    }

    /**
     * 天气
     *
     * @author zengshuai shi
     */
    class Weather extends AsyncTask<String, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... params) {
            JSONObject jsonObject = RequstUtil.getResponseForPost(url, pairs, context);
            return jsonObject;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            if (!CommonUtil.isNull(result)) {
                if (operationCallbackListener != null) {
                    operationCallbackListener.onGaodeCallbackListener(result.toString(), GaodeType.Weather.value());
                } else {
                    operationCallbackListener.onGaodeCallbackListener(null, GaodeType.Weather.value());
                }
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            if (operationCallbackListener != null)
                operationCallbackListener.onGaodeCallbackListener(null, null);
        }
    }


//    /**
//     * 限行
//     *
//     * @author zengshuai shi
//     */
//    class Restrictions extends AsyncTask<String, String, JSONObject> {
//        String plateNum;
//
//        @Override
//        protected JSONObject doInBackground(String... params) {
//            JSONObject jsonObject = RequstUtil.getResponseForGet(url, context);
//            return jsonObject;
//        }
//
//        @Override
//        protected void onPostExecute(JSONObject result) {
//            super.onPostExecute(result);
//            if (operationCallbackListener != null) {
//                if (!CommonUtil.isNull(result)) {
//                    operationCallbackListener.plateNum = plateNum;
//                    operationCallbackListener.onGaodeCallbackListener(result.toString(), GaodeType.Restrictions.value());
//                } else {
//                    operationCallbackListener.onGaodeCallbackListener(null, GaodeType.Restrictions.value());
//                }
//            }
//        }
//
//        @Override
//        protected void onCancelled() {
//            super.onCancelled();
//            if (operationCallbackListener != null)
//                operationCallbackListener.onGaodeCallbackListener(null, GaodeType.Restrictions.value());
//        }
//    }

    /**
     * 查询违章，限行
     * //GaodeType.Violation
     *
     * @param entity
     */
    private void getViolationAndRestrictions(final PlateEngineNumEntity entity, final GaodeType type) {
        ThirdpartyService service = new ThirdpartyService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        requestEntity.setMethod(HttpMethod.GET.value());
//        entity.setVin("G140503");

//        //查询限行时需转成英文城市进行查询
        String city= ((MrOActivity)context).util.getCurrCity();
//        if(context!=null){
//            LoadCityList cityList = new LoadCityList(context);
//            city = cityList.findByZhCity(MrOPoiUtil.getInstance().getCurrCity());
//            city=city.toLowerCase(Locale.CHINA);
//        }
        requestEntity = type.equals(GaodeType.Restrictions) ? service.restrictionQuery(city, requestEntity) : service.violationQuery(entity.getVin(), entity.getLicensePlate(), entity.getEngineNumber(), requestEntity);
        requestEntity.setAccept(HttpAccept.JSON.value());
        requestEntity.setLanguage(Language.ZH.value());
        new Sender().send(requestEntity, new ResponseHandler() {
            @Override
            public void onSuccess(String tag, final String json) {
                MyPost.post(new Runnable() {
                    @Override
                    public void run() {
                        if (operationCallbackListener != null) {
                            if (!CommonUtil.isNull(json)) {
                                operationCallbackListener.plateNum = entity.getLicensePlate();
                                operationCallbackListener.onGaodeCallbackListener(json, type.value());
                            } else {
                                operationCallbackListener.onGaodeCallbackListener(null, type.value());
                            }
                        }
                    }
                });
            }

            @Override
            public void onError(String tag, final HttpException e) {
                MyPost.post(new Runnable() {
                    @Override
                    public void run() {
                        String errorMsg="";
                        try {
                            int errorMsgId = AppRUtils.getInstance(context).getResouceId("string", e.getErrorCode());
                            errorMsg=context.getString(errorMsgId);
                        }catch (Exception e1){
                            e1.printStackTrace();
                            errorMsg=e.getMessage();
                        }
                        operationCallbackListener.onGaodeCallbakError(errorMsg, type.value());

                    }
                });

            }
        });
    }

//    /**
//     * 违章
//     *
//     * @author zengshuai shi
//     */
//    class Violation extends AsyncTask<String, String, JSONObject> {
//        String plateNum;
//
//        @Override
//        protected JSONObject doInBackground(String... params) {
//            JSONObject jsonObject = RequstUtil.getResponseForPost(url, pairs, context);
//            return jsonObject;
//        }
//
//        @Override
//        protected void onPostExecute(JSONObject result) {
//            super.onPostExecute(result);
//            if (operationCallbackListener != null) {
//                if (!CommonUtil.isNull(result)) {
//                    operationCallbackListener.plateNum = plateNum;
//                    operationCallbackListener.onGaodeCallbackListener(result, GaodeType.Violation.value());
//                } else {
//                    operationCallbackListener.onGaodeCallbackListener(null, GaodeType.Violation.value());
//                }
//            }
//        }
//
//        @Override
//        protected void onCancelled() {
//            super.onCancelled();
//            if (operationCallbackListener != null)
//                operationCallbackListener.onGaodeCallbackListener(null, GaodeType.Violation.value());
//        }
//    }


}
